package be.jabapage.snooker.service.importation.impl;

import org.apache.commons.lang.Validate;

import be.jabapage.snooker.container.CompetitionContainer;
import be.jabapage.snooker.exception.EntityNotFoundException;
import be.jabapage.snooker.exception.MultipleInstanceFoundException;
import be.jabapage.snooker.exception.ProcessingException;
import be.jabapage.snooker.jdo.competition.Competition;
import be.jabapage.snooker.service.administration.api.ITeamService;
import be.jabapage.snooker.service.competition.api.ICompetitionService;
import be.jabapage.snooker.service.competition.api.ITeamCompetitionParticipationService;
import be.jabapage.snooker.service.importation.api.ICompetitionImportService;
import be.jabapage.snooker.service.importation.api.ISubCompetitionImportService;
import be.jabapage.snooker.service.overwriter.api.ICompetitionOverwriter;

public class CompetitionImportService implements ICompetitionImportService {

	private final ICompetitionService competitionService;
	private final ICompetitionOverwriter competitionOverwriter;
	private final ISubCompetitionImportService subCompetitionImportService;
	private final ITeamCompetitionParticipationService teamCompetitionParticipationService;
	private final ITeamService teamService;
	
	public CompetitionImportService(
			final ICompetitionService competitionService,
			final ICompetitionOverwriter competitionOverwriter,
			final ISubCompetitionImportService subCompetitionImportService,
			final ITeamCompetitionParticipationService teamCompetitionParticipationService,
			final ITeamService teamService) {
		Validate.notNull(competitionService);
		Validate.notNull(competitionOverwriter);
		Validate.notNull(subCompetitionImportService);
		Validate.notNull(teamCompetitionParticipationService);
		Validate.notNull(teamService);
		this.competitionService = competitionService;
		this.competitionOverwriter = competitionOverwriter;
		this.subCompetitionImportService = subCompetitionImportService;
		this.teamCompetitionParticipationService = teamCompetitionParticipationService;
		this.teamService = teamService;
	}

	public void importCompetition(CompetitionContainer container) throws ProcessingException {
		Validate.notNull(container);
		Competition competition = container.getCompetition();
		Validate.notNull(competition);
		
		try {
			Competition dbCompetition= competitionService.retrieve(competition.getLevel());
			competitionOverwriter.overwrite(dbCompetition, competition);
			competitionService.store(competition);
		} catch (MultipleInstanceFoundException e) {
			throw new ProcessingException("Multiple instances found for this competition name.", e);
		} catch (EntityNotFoundException e) {
			competitionService.store(competition);
		}

	}

}
